from django.contrib.auth.models import AbstractUser
from django.db import models

from course.models import Course
from .contants import (
    GROUP_SUPERVISOR,
    GROUP_TEACHER,
    GROUP_ASSISTANT,
    GROUP_STUDENT,
)


class User(AbstractUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=150, blank=True)
    # sns
    wechat = models.CharField(max_length=20, blank=True, )
    linkedin = models.CharField(max_length=40, blank=True, )
    weibo = models.CharField(max_length=40, blank=True, )
    facebook = models.CharField(max_length=40, blank=True, )
    twitter = models.CharField(max_length=40, blank=True, )
    # others
    mobile = models.CharField(max_length=20, blank=True, )
    docs_url = models.URLField(max_length=100, blank=True)
    bio = models.TextField(max_length=500, blank=True)

    teaching = models.ManyToManyField(Course,
                                      related_name='techers',
                                      blank=True)
    enrolling = models.ManyToManyField(Course,
                                       related_name='students',
                                       blank=True)

    current_group = models.CharField(max_length=20, null=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['']

    class Meta(object):
        unique_together = ('email',)

    def is_in_group(self, group_name):
        if not self.current_group:
            if self.groups.filter(name=GROUP_SUPERVISOR).exists():
                self.current_group = GROUP_SUPERVISOR
            elif self.groups.filter(name=GROUP_TEACHER).exists():
                self.current_group = GROUP_TEACHER
            elif self.groups.filter(name=GROUP_ASSISTANT).exists():
                self.current_group = GROUP_ASSISTANT
            else:
                self.current_group = GROUP_STUDENT
            self.save()

        return self.current_group == group_name

    def save(self, *args, **kwargs):
        if not self.username:
            self.username = '{} {}'.format(self.first_name, self.last_name)
            # print('set username', self.username)

        super(User, self).save(*args, **kwargs)

    @property
    def get_first_enrollment(self):
        history = EnrollmentHistory.objects.filter(user=self) \
                                   .order_by('-date').first()
        if history:
            return '{} - {}'.format(history.course.full_name,
                                    history.date.strftime("%Y-%m-%d"))
        else:
            return 'no enrollment'

    @property
    def get_latest_resumes(self):
        resume_types = self.resumes.values('desc').distinct()
        selected_ids = []
        for obj in resume_types:
            resume = self.resumes.filter(
                desc=obj['desc']).order_by('-created_date').first()
            selected_ids.append(resume.id)
        queryset = self.resumes.filter(
            id__in=selected_ids).order_by('-created_date')
        return queryset

    def __str__(self):
        return self.username


class EnrollmentHistory(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE,
        related_name='enrollment'
    )
    course = models.ForeignKey(
        Course, on_delete=models.CASCADE,
        related_name='enrollment'
    )
    date = models.DateTimeField(null=True)

    def __str__(self):
        return '{}: {}: {}'.format(self.user.username, self.course, self.date)

    def save(self, *args, **kwargs):
        # print('save')
        super(EnrollmentHistory, self).save(*args, **kwargs)

        # if EnrollmentHistory.objects.filter(user=self.user).count() == 1:
        #     username = '{}_{}_{}_{}'.format(
        #         self.user.last_name,
        #         self.user.first_name,
        #         self.course.full_name,
        #         self.date.strftime("%Y-%m-%d")
        #     )
        #     self.user.username = username
        #     self.user.save()
        #     print('set username: ', username)


class WorkExperience(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE,
        related_name='work_exp'
    )
    company = models.CharField(max_length=50, )
    position = models.CharField(max_length=50, )
    start = models.DateField()
    end = models.DateField(blank=True, null=True, )
    remarks = models.TextField(blank=True, null=True, )


class StudyExperience(models.Model):
    BA = 'BA'
    BS = 'BS'
    MA = 'MA'
    MS = 'MS'
    PhD = 'PhD'
    Others = 'Others'
    DEGREE_CHOICES = (
        (BA, 'BA'),
        (BS, 'BS'),
        (MA, 'MA'),
        (MS, 'MS'),
        (PhD, 'PhD'),
        (Others, 'Others'),
    )

    user = models.ForeignKey(
        User, on_delete=models.CASCADE,
        related_name='study_exp'
    )
    college = models.CharField(max_length=50, )
    major = models.CharField(max_length=50, )
    degree = models.CharField(
        max_length=10,
        choices=DEGREE_CHOICES,
        default=BS,
    )
    start = models.DateField()
    end = models.DateField(blank=True, null=True,)
    remarks = models.TextField(blank=True, null=True, )
